import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const billStore = createSlice({
    name: "bill",
    initialState:{
        billList:[]
    },
    reducers:{
        setBillList(state, action){
            state.billList = action.payload
        },
        //同步添加账单方法
        addBill(state, action){
            state.billList.push(action.payload)
        }
    }
})

const {setBillList, addBill} = billStore.actions
export {setBillList, addBill} 

const reducer = billStore.reducer
export default reducer

//异步获取帐单列表
const getBillList = () => {
    return async(dispatch)=>{
        const res = await axios.get('http://localhost:6688/ka') 
        dispatch(setBillList(res.data))
    }
}

//异步新增帐单列表
const addBillList = (data) => {
    return async(dispatch)=>{
        const res = await axios.post('http://localhost:6688/ka', data) 
        dispatch(addBill(res.data))
    }
}

export {getBillList, addBillList}